<?php
class Documents_model extends MY_Model {
	private $module = 'documents';
	private $table = 'document';

	function getsearchContent($limit,$page){
		$this->db->select('*');
		$this->db->limit($limit,$page);
		$this->db->order_by($this->input->post('func_order_by'),$this->input->post('order_by'));
		if($this->input->post('content')!='' && $this->input->post('content')!='type here...'){
			$this->db->where('(`title` LIKE "%'.$this->input->post('content').'%")');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')==''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
		}
		if($this->input->post('dateFrom')=='' && $this->input->post('dateTo')!=''){
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')!=''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}

	function getTotalsearchContent(){
		$this->db->select('*');
		if($this->input->post('content')!='' && $this->input->post('content')!='type here...'){
			$this->db->where('(`title` LIKE "%'.$this->input->post('content').'%")');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')==''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
		}
		if($this->input->post('dateFrom')=='' && $this->input->post('dateTo')!=''){
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')!=''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		$query = $this->db->count_all_results(PREFIX.$this->table);

		if($query > 0){
			return $query;
		}else{
			return false;
		}
	}

	function getDetailManagement($id){
		$this->db->select('*');
		$this->db->where('id',$id);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}

	function saveManagement($fileName=''){
		if($this->input->post('statusAdmincp')=='on'){
			$status = 1;
		}else{
			$status = 0;
		}
		//upload document
		$document = (isset($_FILES['fileAdmincp'])) ? $this->Upload($_FILES['fileAdmincp']) : '';

		//get selected group can download file
		$groups_tmp = $this->input->post('group');
		$groups = '';
		foreach ($groups_tmp as $key => $value) {
			$groups = $groups . $value . ',';
		}

		if($this->input->post('hiddenIdAdmincp')==0){
			//Kiểm tra đã tồn tại chưa?
			$checkData = $this->checkData($this->input->post('titleAdmincp'));
			if($checkData){
				print 'error-title-exists';
				exit;
			}

			$data = array(
				'title'=> $this->input->post('titleAdmincp'),
				'link'=> $document,
				//'order_view'=> $this->input->post('order_viewAdmincp'),
				'groups' => $groups,
				'status'=> $status,
				'created'=> date('Y-m-d H:i:s',time()),
			);
			if($this->db->insert(PREFIX.$this->table,$data)){
				modules::run('admincp/saveLog',$this->module,$this->db->insert_id(),'Add new','Add new');
				return true;
			}
		}else{
			$result = $this->getDetailManagement($this->input->post('hiddenIdAdmincp'));
			//Kiểm tra đã tồn tại chưa?
			if($result[0]->title!=$this->input->post('titleAdmincp')){
				$checkData = $this->checkData($this->input->post('titleAdmincp'));
				if($checkData){
					print 'error-title-exists';
					exit;
				}
			}

			//Xử lý xóa file khi update thay đổi file
			if (isset($_FILES['fileAdmincp']) && $_FILES['fileAdmincp']['error'] == 0) {
          @unlink(DIR_DOCUMENT . $result[0]->link);
     	}

			$data = array(
				'title'=> $this->input->post('titleAdmincp'),
				'link'=> !empty($document)?$document:$result[0]->link,
				//'order_view'=> $this->input->post('order_viewAdmincp'),
				'groups' => $groups,
				'status'=> $status,
				'modified'=> date('Y-m-d H:i:s',time()),
			);
			modules::run('admincp/saveLog',$this->module,$this->input->post('hiddenIdAdmincp'),'','Update',$result,$data);
			$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
			if($this->db->update(PREFIX.$this->table,$data)){
				return true;
			}
		}
		return false;
	}

	function Upload($file = '', $folder = '') {
      if ($file['error'] != 0)
         return false;
      if (!empty($folder)) {
         $uploadDir = $folder;
      } else {
         $uploadDir = DIR_DOCUMENT;
      }

      $uploadDir = $uploadDir . get_folder();
      Newfolder($uploadDir);

      $tmp_name = $file['tmp_name'];
      $path_parts = pathinfo($file['name']);
      $path_parts['dirname'];
      $path_parts['basename'];
      $path_parts['extension'];
      $path_parts['filename'];
      //TODO: Lay extesion
      $ext = strtolower($path_parts['extension']);
      $name = md5(uniqid(mt_rand())) . '_' . time() . "." . $ext;
      $file_info = get_folder() . $name;
      if (move_uploaded_file($tmp_name, $uploadDir . $name)) {
         //upload img thanh cong
         return $file_info;
      } else {
         return false;
      }//else
   }

//Upload

	function checkData($title){
		$this->db->select('id');
		$this->db->where('title',$title);
		$this->db->limit(1);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return true;
		}else{
			return false;
		}
	}

	function checkSlug($slug){
		$this->db->select('id');
		$this->db->where('slug',$slug);
		$this->db->limit(1);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return true;
		}else{
			return false;
		}
	}

	function _get_user_groups(){
		$this->db->select('*');
		$this->db->where('status',1);
		$query = $this->db->get(PREFIX.'groups');
		if($query->result()){
			return $query->result();
		}
		else
			return false;
	}

	private function _getParent($parent_id){
		$this->db->select('*');
		$this->db->where('id',$parent_id);
		$query = $this->db->get(PREFIX.'category');
		if($query->result()){
			return $query->row();
		}
		else
			return false;
	}

	private function _getSingleNews($current_slug){
		$this->db->select('*');
		$this->db->where('slug',$current_slug);
		$query = $this->db->get(PREFIX.'news');
		if($query->result()){
			return $query->row();
		}
		else
			return false;
	}

	private function _updateLink($current_slug = '', $parent_id = 0) {
		if($parent_id != 0){
			$parent = $this->_getParent($parent_id);
			$current = $this->_getSingleNews($current_slug);
			$link = $parent->link . '/' . $current_slug;
			$data['link'] = $link;
      $this->model->update(PREFIX.'news', $data, "id = $current->id");
      //pr($this->db->last_query(),1);
		}
	}

	private function _updateMenuLink($parent_id = 0, $parent_link = '') {
    $article_list = $this->model->fetch('id,parent_id,slug', PREFIX.'category', "parent_id = $parent_id", 'id', 'ASC');
    if (!empty($article_list)) {
      foreach ($article_list as $article) {
        $current_id = $article->id;
        $link = $article->slug;
        if (!empty($parent_link)) {
           $link = $parent_link . '/' . $link;
        }
        $data['link'] = $link;
        $this->model->update(PREFIX.'news', $data, "id = $current_id");
        $this->_updateMenuLink($current_id, $link);
      }
    }
	}

	function getCategory(){
		$this->db->select('*');
		$this->db->where('status',1);
		$query = $this->db->get(PREFIX.'category');
		if($query->result()){
			return $query->result();
		}
		else{
			return false;
		}
	}

	/*----------------------FRONTEND----------------------*/
	function getNews($type){
		$this->db->select('*');
		$this->db->where('type',$type);
		$this->db->where('status',1);
		$this->db->order_by('created','DESC');
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}

	function getNewsDetail($slug_detail){
		$this->db->select('id,content');
		$this->db->where('slug',$slug_detail);
		$this->db->where('status',1);
		$this->db->limit(1);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	/*--------------------END FRONTEND--------------------*/
}
